package org.elephas.webapp.frontend.component;

import java.util.Iterator;
import java.util.List;

import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.RefreshingView;
import org.apache.wicket.markup.repeater.util.ModelIteratorAdapter;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.elephas.model.Post;
import org.elephas.service.PostFinder;
import org.elephas.webapp.model.DetachableBlogModel;
import org.elephas.webapp.model.DetachablePostModel;

/**
 * Shows the latest posts either per blog or across all blogs.
 * 
 * TODO: make this class more generic, so that various filters (eg year, tags,
 * ...) can be applied
 * 
 * @author Gerolf Seitz
 * 
 */
public class RecentPostsPanel extends Panel {

	private static final long serialVersionUID = 1L;

	@SpringBean
	private PostFinder finder;

	/**
	 * Constructs the panel with posts either for a specific blog or across all
	 * blogs in case the parameter blog is null.
	 * 
	 * @param id
	 *            the component id
	 * @param blogModel
	 *            the blog containing the posts, or null for posts across all
	 *            blogs
	 * @param nrOfPosts
	 *            the number of posts that are shown
	 */
	public RecentPostsPanel(String id, final DetachableBlogModel blogModel,
			final int nrOfPosts) {
		super(id);

		RefreshingView latestPosts = new RefreshingView("postPreviewList") {
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(Item item) {
				item.add(new PostPreviewPanel("postPreview",
						(DetachablePostModel) item.getModel()));
			}

			@Override
			protected Iterator<?> getItemModels() {
				List<Post> posts = findPosts();
				return new ModelIteratorAdapter(posts.iterator()) {
					@Override
					protected IModel model(Object object) {
						return new DetachablePostModel((Post) object);
					}
				};
			}

			private List<Post> findPosts() {
				if (blogModel == null) {
					return finder.loadRecentPosts(nrOfPosts);
				} else {
					return blogModel.getObject().getRecentPosts(nrOfPosts);
				}
			}
		};
		add(latestPosts);
	}
}
